package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.mapper.SysRoleMenuMapper;
import com.atguigu.spzx.manager.service.SysMenuService;
import com.atguigu.spzx.manager.service.SysRoleMenuService;
import com.atguigu.spzx.model.entity.sys.SysMenu;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {
    @Resource
    SysMenuMapper  sysMenuMapper;
    @Resource
    SysRoleMenuMapper sysRoleMenuMapper;
    @Override
    public Map<String, Object> findMenusByRoleId(Long roleId) {
        //查询所有的菜单 并且挑选可用菜单列表
        List<SysMenu> menus = sysMenuMapper.findAll()
                .stream().filter(sysMenu -> sysMenu.getStatus().intValue()==1)
                .collect(Collectors.toList());
        //将菜单组装成父子菜单集合
        List<SysMenu> parents = menus.stream().filter(sysMenu -> sysMenu.getParentId().longValue() == 0l)
                .collect(Collectors.toList());
        buildMenuTree(menus , parents);
        //查询角色的已分配的菜单id集合
        List<Long> menuIds = sysRoleMenuMapper.findMenuIdsByRoleId(roleId);



        //组装数据返回
        Map<String, Object> map = new HashMap<>();
        //返回组装好的菜单列表
        map.put("menus",parents);
        map.put("menuIds",menuIds);
        return map;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assignMenus2Role(Long roleId, List<Long> menuIds) {
        //删除角色所有的已分配的菜单:物理删除
        sysRoleMenuMapper.deleteByRoleId(roleId);
        //给roleId分配菜单
        sysRoleMenuMapper.assignMenus2Role(roleId,menuIds);

    }

    private void buildMenuTree(List<SysMenu> all , List<SysMenu> parents){
        if(CollectionUtils.isEmpty(parents)){
            return;
        }
        parents.forEach(parent->{
            List<SysMenu> children = all.stream().filter(sysMenu ->
                            sysMenu.getParentId().longValue() == parent.getId().longValue())
                    .collect(Collectors.toList());
            parent.setChildren(children);
            //children可能也有下一级菜单
            buildMenuTree(all , children);
        });
    }
}
